package com.miraclemiles.oauth.service;

import com.miraclemiles.oauth.entity.SysUser;
import com.miraclemiles.oauth.mapper.SysUserMapper;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Optional;

@AllArgsConstructor
@Service
public class OauthUserDetailsService implements UserDetailsService {

    private final SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) {

        SysUser user = Optional.ofNullable(sysUserMapper.selectUserByUsername(username)).orElseThrow(() -> new UsernameNotFoundException("用户不存在"));

        if (!user.getEnabled()) {
            throw new DisabledException("用户已禁用");
        }

        return new LoginUser(user.getId(), user.getNickName(), user.getAvatar(), user.getMobile(), user.getUsername(), user.getPassword(),
                //账户已禁用
                user.getEnabled(),
                //账户已过期
                true,
                //凭证已过期
                true,
                //账户已锁定
                true,
                //TODO 权限暂时空（角色代码：ROLE_）
                new ArrayList<SimpleGrantedAuthority>());
    }

}
